<?php

declare(strict_types=1);

namespace App\Chat\Process;

use App\Chat\Constant\RedisSubscribeChan;
use App\Chat\Service\Message\SubscribeHandleService;
use Hyperf\Process\AbstractProcess;
use Hyperf\Process\Annotation\Process;

//#[Process(name: 'RedisWebsocketSubscribe')]
class RedisWebsocketSubscribe extends AbstractProcess
{

    /**
     * 订阅的通道
     *
     * @var string[]
     */
    private $chans = [
        RedisSubscribeChan::WEBSOCKET_CHAN
    ];

    /**
     * @var SubscribeHandleService
     */
    private $handleService;

    public function handle(): void
    {
        stdout_log()->info("Starting Redis subscription");

        $this->handleService = di()->get(SubscribeHandleService::class);
        $redis = redis();
        $redis->setOption(\Redis::OPT_READ_TIMEOUT, -1);
        $redis->subscribe($this->chans, [$this, 'subscribe']);

//        while (true) {
//            try {
//                stdout_log()->info("Starting Redis subscription");
//                $this->handleService = di()->get(SubscribeHandleService::class);
//
//                redis()->subscribe($this->chans, [$this, 'subscribe']);
//                // 如果订阅意外结束，等待后重试
//                sleep(1);
//            } catch (\Throwable $e) {
//                stdout_log()->error("Process error: ".$e->getMessage());
//                sleep(1);
//            }
//        }
    }

    /**
     * 订阅处理逻辑
     *
     * @param        $redis
     * @param string $chan
     * @param string $message
     */
    public function subscribe($redis, string $chan, string $message)
    {
        stdout_log()->info("chan : $chan , msg : $message");
        
        $data = json_decode($message, true);
        $this->handleService->handle($data);
    }

}